// pages/itra/itra.js
import Toast from 'tdesign-miniprogram/toast/index';
var StringUtil = require('../../utils/string.js');
const STORAGE_KEY_FAV = 'FAV-KEY';

Page({
  getInstance() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar((tabBar) => {
        tabBar.setData({
          selected: 0
        })
      })
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    //搜索字段
    firstName: '',
    lastName: '',
    birthYear: '',
    start: 1,

    //展示控制
    birthYearPickerVisible: false,
    birthYearText: "选填",
    firstNameStatus: "success",
    lastNameStatus: "success",
    firstNameTips: "",
    lastNameTips: "",
    resultList: [],
    resultVisible: false,
    isSearching: false,
    alots: false,

    //初始化数据
    favRunners: [],
    years: [],
    defaultBirthYear: [1990]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // const yearsList = [];
    // const currentYear = new Date().getFullYear();
    // for (let index = currentYear - 100; index < currentYear + 1; index++) {
    //   yearsList.push({
    //     label: index + '年',
    //     value: index
    //   });
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar((tabBar) => {
        const page = getCurrentPages().pop();
        const route = page ? page.route.split('?')[0] : '';
        tabBar.setData({
          value: "/" + route
        })
      })
    }

    let favRunnersData = wx.getStorageSync(STORAGE_KEY_FAV);
    var favRunners = favRunnersData ? JSON.parse(favRunnersData) : {};
    this.setData({
      favRunners: Object.keys(favRunners).map(e => favRunners[e]).sort(function (a, b) {
        return a.pi < b.pi ? 1 : -1; // 降序排列
      }),
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  firstNameChange(e) {
    this.setData({
      firstName: e.detail.value
    });
  },
  lastNameChange(e) {
    this.setData({
      lastName: e.detail.value
    });
  },
  birthYearChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      birthYearPickerVisible: false,
      birthYear: value[0], //picker的value是数组类型
      birthYearText: value + "年",
    });
  },
  onBirthYearPicker(e) {
    this.setData({
      birthYearPickerVisible: true,
    });
  },
  onPickerCancel(e) {
    this.setData({
      birthYearPickerVisible: false,
    });
  },
  onVisibleChange(e) {
    this.setData({
      resultVisible: e.detail.visible
    });
  },
  addToFav(e) {
    var runner = e.currentTarget.dataset.runner;
    let favRunnersData = wx.getStorageSync(STORAGE_KEY_FAV);
    var favRunners = favRunnersData ? JSON.parse(favRunnersData) : {};
    var favStatus;
    if (favRunners[runner.runnerId]) {
      delete favRunners[runner.runnerId];
      favStatus = "no";
      Toast({
        context: this,
        selector: '#t-toast',
        message: '已取消收藏',
        theme: 'warning',
        direction: 'column',
        duration: 800
      });
    } else {
      favRunners[runner.runnerId] = runner;
      favStatus = "yes";
      Toast({
        context: this,
        selector: '#t-toast',
        message: '已收藏',
        theme: 'success',
        direction: 'column',
        duration: 800
      });
    }
    var filterRunner = this.data.resultList.find(function (row, index, arrs) {
      return row.runnerId === runner.runnerId
    });
    filterRunner.favStatus = favStatus;
    wx.setStorage({
      key: STORAGE_KEY_FAV,
      data: JSON.stringify(favRunners),
    });
    favRunnersData = wx.getStorageSync(STORAGE_KEY_FAV);

    this.setData({
      favRunners: Object.keys(favRunners).map(e => favRunners[e]).sort(function (a, b) {
        return a.pi < b.pi ? 1 : -1; // 降序排列
      }),
      resultList: this.data.resultList
    });
  },
  goDetail(e) {
    wx.navigateTo({
      url: '/pages/detail/detail?runner=' + JSON.stringify(e.currentTarget.dataset.runner)
    })
  },
  search() {
    var firstNameEmpty = this.strIsEmpty(this.data.firstName);
    var lastNameEmpty = this.strIsEmpty(this.data.lastName);
    let favRunnersData = wx.getStorageSync(STORAGE_KEY_FAV);
    var favRunners = favRunnersData ? JSON.parse(favRunnersData) : {};
    if (firstNameEmpty) {
      this.setData({
        firstNameStatus: "error",
        firstNameTips: "不能为空",
        isSearching: false
      });
    } else {
      this.setData({
        firstNameStatus: "success",
        firstNameTips: "",
        isSearching: true
      });
    }

    if (lastNameEmpty) {
      this.setData({
        lastNameStatus: "error",
        lastNameTips: "不能为空",
        isSearching: false
      });
    } else {
      this.setData({
        lastNameStatus: "success",
        lastNameTips: "",
        isSearching: true
      });
    }
    if (!firstNameEmpty && !lastNameEmpty) {
      const name = this.data.firstName + " " + this.data.lastName;
      wx.cloud.callFunction({
        name: "api_proxy",
        data: {
          url: "https://zhizhangcs.cn/itra.php",
          method: 'POST',
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
          },
          form: {
            name: name,
            start: this.start,
            count: 30
          }
        },
        success: (res) => {
          this.setData({
            isSearching: false
          });
          if (res.result.results && res.result.results.length > 0) {
            res.result.results.forEach(row => {
              var isFav = favRunners && favRunners[row.runnerId];
              row.favStatus = isFav ? "yes" : "no";
              row.recentRaces = row.recentRaces.split("|");
              row.firstName = StringUtil.toSUpper(row.firstName);
              row.lastName = StringUtil.toSUpper(row.lastName);
            });
            this.setData({
              resultVisible: true,
              resultList: res.result.results,
              alots: res.result.resultCount > 2
            });
          } else {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '找不到选手' + name + '\n最近的比赛记录',
              theme: 'error',
              direction: 'column',
            });
          }
        },
        fail: (res) => {
          this.setData({
            isSearching: false
          });
          Toast({
            context: this,
            selector: '#t-toast',
            message: '查询失败，请稍后重试',
            theme: 'error',
            direction: 'column',
          });
        }
      })

    }
  },
  strIsEmpty(str) {
    return !str || str.trim().length === 0;
  }
})